package com.longrise.android.byjk.plugins.dealsituation.course.video2.education.picedu;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BasePresenter;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.AssistCache;
import com.longrise.android.byjk.plugins.dealsituation.course.exercises.ExercisesActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.StudyRecordBase;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.study.DefendHandler;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.study.LoadVideoInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.study.LoopRecord;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;

import org.greenrobot.eventbus.EventBus;

import static com.longrise.common.utils.AppUtil.getString;


/**
 * Created by godliness on 2017/7/31.
 */

public class PicPrecenter extends BasePresenter<PicView> {

    private static final String TAG = "PicPrecenter";

    /**
     * 获取课件资源时
     */
    private final int GET_CWID_RESOURCE = 0;
    /**
     * 维护过程时
     */
    private final int MONITOR_STUDY = 1;
    private int mCurrentErrorType = GET_CWID_RESOURCE;

    private int mCourseCount;

    /**
     * 课件状态学习
     */
    private final StudyRecordBase.StudyState mStudyState = StudyRecordBase.getStudyStateInstance();

    /**
     * 学习记录id
     */
    private String mRecordid;

    boolean upLoaded = false;

    @Override
    protected void init() {
        mView.setTitle("");
    }

    /**
     * 1、获取图片资源
     * 2、执行维护过程（同步学习）
     * 图片课件较短，为保证图片课件直接通过时，首先执行1，如果isFinish==true，直接展示资源。
     * 如果isFinish==false，执行2，成功后在展示资源
     * <p>
     * 过程中出错处理：如果执行1，出错mCurrentErrorType == GET_CWID_RESOURCE 代表获取资源时出错，
     * 如果执行2，出错 mCurrentErrorType == MONITOR_STUDY 代表维护过程出错
     * 默认 mCurrentErrorType == GET_CWID_RESOURCE
     * <p>
     * 在PictureActivity执行onReload()时，根据mCurrentErrorType条件执行相应任务。
     */
    public void reLoad() {
        if (mCurrentErrorType == GET_CWID_RESOURCE) {
            toRequstResource();
        } else {
            toUploadStudy();
        }
    }

    /**
     * 刷新课程详情 reload
     */
    public void toRefrushCourseDetail() {
        if (upLoaded) {
//            Intent courseDetailIntent = new Intent(MessageConstants.PAY_SUCCESS);
//            courseDetailIntent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.REFRESH_DETIAL);
//            mContext.sendBroadcast(courseDetailIntent);

            CourseDetailEvent event = new CourseDetailEvent();
            event.setRefreshDetail(true);
            EventBus.getDefault().post(event);
        }
    }

    /**
     * 课后习题逻辑
     */
    public void exerciseOptions() throws Exception {
        boolean hasqa = mStudyState.mHasqa;
        if (!hasqa) {
            return;
        }
        boolean isFinish = mStudyState.mIsFinish;
        if (isFinish) {
            //立即查看课后习题
            cwidHasqaDialog(true);
            return;
        }
        boolean isVideopass = mStudyState.mVideoPass;
        if (isVideopass) {
            cwidHasqaDialog(false);
            return;
        }
    }

    /**
     * 课后习题
     */
    private void toHasqaActivity() {
        VideoParams videoParams = mView.getVideoParams();
        if (videoParams == null) {
            return;
        }
        Intent intent = new Intent(mContext, ExercisesActivity.class);
        intent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, videoParams);
        mContext.startActivity(intent);
        mView.onBack();
    }

    /**
     * 课后习题dialog
     */
    private void cwidHasqaDialog(boolean isFinish) throws Exception {
        if (mView.actFinished()) {
            return;
        }
        View v = View.inflate(mContext, R.layout.dialog_clearcache, null);
        final TextView textTitle = (TextView) v.findViewById(R.id.text_course_title);
        textTitle.setText(getString(R.string.videofinish_testtitle));
        final TextView textContent = (TextView) v.findViewById(R.id.text_);
        textContent.setText(isFinish ? getString(R.string.cwidfinish_testhint) : getString(R.string.videofinish_testhint));
        final TextView textCancle = (TextView) v.findViewById(R.id.text_cancle);
        textCancle.setText(getString(R.string.videofinish_testcancle));
        final TextView textConfrim = (TextView) v.findViewById(R.id.text_confirm);
        textConfrim.setText(isFinish ? getString(R.string.videofinish_testshow) : getString(R.string.videofinish_testconfrim));
        View.OnClickListener mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dismiss();
                switch (v.getId()) {
                    case R.id.text_cancle:
                        Tracker_Google.getInstance().addEvent("Excercise-after", "Next-time", "下次再说");
                        break;
                    case R.id.text_confirm:
                        toHasqaActivity();
                        Tracker_Google.getInstance().addEvent("Excercise-after", "do-now", "立即做题");
                        break;
                    default:
                        break;
                }
            }
        };
        textConfrim.setOnClickListener(mOnClickListener);
        textCancle.setOnClickListener(mOnClickListener);
        DialogUtil.getInstance().creatAlertDialog(mContext, v, 266, 171);
    }

    /**
     * 设置当前学习索引位置
     */
    public void setCurrentPosition(int position) {
        int value = ++position;
        mView.setRightTv(new StringBuilder(String.valueOf(value)).append("/").append(mCourseCount).toString());

        if (value >= mCourseCount) {
            try {
                exerciseOptions();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 加载课件资源
     */
    private void toRequstResource() {
        mView.showLoadingDialog();
        LoadVideoInfor.loadVideoPlayInfor(genratorRecord(), new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                if (mView.actFinished()) {
                    return;
                }
                if (result instanceof EntityBean) {
                    EntityBean resultBean = (EntityBean) result;
                    int resultState = resultBean.getInt("resultstate");
                    if (resultState != 1) {
                        mView.showToast(resultBean.getString("resultdesc"));
                        return;
                    }
                    parse(resultBean.getBean("result"));
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                mCurrentErrorType = GET_CWID_RESOURCE;
                mView.error();
            }

            @Override
            public void onFinished(String key, String service) {

            }
        });
    }

    /**
     * upload 图片资源只要调用该接口直接通过
     */
    private void toUploadStudy() {
        LoopRecord.loop(genratorRecord(), new DefendHandler.OnDefend() {
            @Override
            public void onDefend(boolean videopass) {
                mView.dismissLoadingDialog();
                if (videopass) {
                    updateCwidState();
                }
            }

            @Override
            public void onError() {
                mCurrentErrorType = MONITOR_STUDY;
                mView.error();
            }
        });
    }

    private void updateCwidState() {
        boolean videoPass = mStudyState.mVideoPass;
        boolean hasqa = mStudyState.mHasqa;
        if (!videoPass && !hasqa) {
            upLoaded = true;
        }
        //VideoState.cwidLocal == null 从下载进来获取不到[group,child]
        if (upLoaded) {
            VideoParams vp = mView.getVideoParams();
            sendUpdateMessage(vp);
        }
        //必须最后更新当前课件通过状态
        mStudyState.mVideoPass = true;
    }


    private void sendUpdateMessage(VideoParams params) {
        if (params.mCwidLocal == null) {
            //如果在课程详情页进入，该值为null，不发送消息
            return;
        }
        //更新已缓存课件状态
        boolean cacheUpdated = AssistCache.updateCwidStateInCache(params.mCourseId, params.mCwidLocal);
        if (cacheUpdated) {
            //如果更新成功通知课程详情页根据索引位置更新课件状态
            CourseDetailEvent event = new CourseDetailEvent();
            event.setCoursePosition(params.mCwidLocal);
            EventBus.getDefault().post(event);

        } else {
            //如果更新失败，直接通知课程详情页toRefrush()
            CourseDetailEvent event = new CourseDetailEvent();
            event.setRefreshDetail(true);
            EventBus.getDefault().post(event);
        }
    }




    private void parse(EntityBean bean) {
        if (bean != null) {
            mStudyState.mIsFinish = bean.getBoolean("isfinish");
            mStudyState.mHasqa = bean.getBoolean("ishasqa");
            mStudyState.mVideoPass = bean.getBoolean("isvideopass");
            mRecordid = bean.getString("recordid");
            if (strIsEmpty(mRecordid)) {
                mView.showToast("课件学习记录异常");
                mView.error();
                return;
            }
            EntityBean[] items = bean.getBeans("picSource");
            if (items == null) {
                mView.showToast("课件配置节点异常");
                mView.error();
                return;
            }
            mCourseCount = items.length;
            mView.parse(items);
            if (mStudyState.mIsFinish) {
                mView.dismissLoadingDialog();
            } else {
                //保证图片课件学习直接通过，如果课件是未通过状态：在调用获取资源接口成功，直接调用维护过程（同步记录）
                toUploadStudy();
            }
            PrintLog.e(TAG, "mIsfinish: " + mStudyState.mIsFinish + "  mHasqa： " + mStudyState.mHasqa);
            setCurrentPosition(0);
            try {
                exerciseOptions();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean strIsEmpty(String str) {
        return TextUtils.isEmpty(str);
    }

    /**
     * 封装参数
     */
    private StudyRecordBase.Record genratorRecord() {
        VideoParams videoParams = mView.getVideoParams();
        if (videoParams != null) {
            StudyRecordBase.Record record = StudyRecordBase.getRecordInstance();
            record.mCourseid = videoParams.mCourseId;
            record.mCwid = videoParams.mCwid;
            record.mPathno = videoParams.mPathNo;
            record.mStudentno = videoParams.mStudentNo;
            record.mId = mRecordid;
            record.mDuration = 1; //该值默认传递1
            record.mPosition = 1;
            return record;
        }
        return null;
    }
}
